/* eslint-disable @typescript-eslint/no-shadow */
/*
 * @Author: zy
 * @Date: 2021-10-21 09:10:43
 * @Last Modified by: lt
 * @Last Modified time: 2021-10-25 17:21:31
 */

import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Card,
  Form,
  Select,
  Space,
  Row,
  Col,
  Button,
  Pagination,
  Popconfirm,
  message,
  Input,
} from 'antd';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import type { ActionType } from '@ant-design/pro-table';
import UpdateModal from './components/Modal/BookUpdateModal';
import BookDemageModal from './components/Modal/BookDemageModal';
import type { BookTypesItemType, BookInfoType, BookTypeItem } from '@/services/book';
import { formatDate } from '@/utils/utils';
import { getBookList, getBookType, getBookInfo, getAllType, delBook } from '@/services/book';

const BookManage = () => {
  const [form] = Form.useForm(); // 表单对象
  const pageSizeOptions = ['10', '20', '50']; //分页选择范围
  const ref = useRef<ActionType>(); //tableRef

  const [page, setPage] = useState<number>(1); // 设置当前页
  const [pageSize, setPageSize] = useState<number>(10); // 设置当前页记录条数
  const [total, setTotal] = useState<number>(); //查询记录数

  const [searchKey, setSearchKey] = useState<string>(); //设置搜索关键字
  const [typeAid, setTypeAid] = useState<number>(); //设置图书类型aid
  const [bookTypes, setBookTypes] = useState<BookTypesItemType[]>([]); //设置Select图书类型数据
  const [bookNumber, setBookNumber] = useState<number>(0); //设置查询到的图书总量

  const [updateModalVisible, setUpdateModalVisible] = useState(false); // 设置新增修改modal是否显示
  const [damageModalVisible, setDamageModalVisible] = useState(false); // 设置确认损坏modal是否显示
  const [modifyAid, setModifyAid] = useState<number>(-1); //设置数据的唯一标识（-1为新增）
  const [operation, setOperation] = useState<number>(-1); //设置当前正在进行的操作,（-1:初始化状态，0：新增图书，1：修改图书，2：损坏图书）
  const [bookInfo, setBookInfo] = useState<BookInfoType>(); //设置UpdateModal的数据
  const [modalBookTypes, setModalBookTypes] = useState<BookTypeItem[] | []>([]); //设置updateModal的TreeSelect数据

  /**
   * @description: 获取修改时图书信息（1、传入数据调用接口，将返回数据设置为修改时自动填充的数据
   *                            2、调用接口，将返回数据设置为修改时TreeSelect数据）
   */
  const getModalBookInfo = async (aid?: number) => {
    if (aid) {
      const params = { aid };
      const msg = await getBookInfo(params);
      setBookInfo(msg?.data);
    }
    const data = await getAllType();
    setModalBookTypes(data.data);
  };

  /**
   * @description: 获取搜索栏图书类型
   */

  const getBookTypeList = async () => {
    const msg = await getBookType();
    setBookTypes(msg.data);
  };

  /**
   * @description: 打开页面时首次获取数据
   */

  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      getBookTypeList();
    }
    return function cleanup() {
      mounted = false;
    };
  }, []);

  /**
   * @description: 页面刷新（根据当前页、每页记录数的变化进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      //Do Something
      ref.current?.reload();
    }
    return function cleanup() {
      mounted = false;
    };
  }, [page, pageSize]);
  /**
   * @description: 页面刷新（根据新增修改modal、损坏modal的变化且都处于关闭状态时进行页面刷新）
   */
  useEffect(() => {
    let mounted = true;
    if (mounted) {
      if (!updateModalVisible && !damageModalVisible) {
        ref.current?.reload();
      }
    }
    return function cleanup() {
      mounted = false;
    };
  }, [updateModalVisible, damageModalVisible]);
  /**
   * @description: table数据请求（1、判断searchKey、typeAid是否存在值，将判断后的数据传给相应后端
   *                             2、渲染返回数据（正常数据或查询数据），并进行信息提示）
   */
  const requestHandler = async () => {
    const pagination = { page, pageSize };
    let params;
    if (searchKey && typeAid) {
      params = { searchKey, typeAid, ...pagination };
    } else if (searchKey) {
      params = { searchKey, ...pagination };
    } else if (typeAid) {
      params = { searchKey, typeAid, ...pagination };
    } else {
      params = pagination;
    }
    const msg = await getBookList(params);
    if (msg?.code === 10000) {
      setTotal(msg.data.rowNumber);
      setBookNumber(msg.data.totalNumber);
      return {
        data: msg?.data?.list,
        success: true,
        total: msg?.data.rowNumber,
      };
    } else {
      message.error(msg ? msg.message : '网络异常');
      return {
        data: undefined,
        success: false,
        total: 0,
      };
    }
  };

  /**
   * @description: 分页设置（设置当前页和每页记录数）
   */
  const paginationChangeHandler = (_page: number, _per_page: any) => {
    setPage(_page);
    setPageSize(_per_page);
  };

  /**
   * @description: 搜索表单提交（传入关键字数据并进行设置，刷新页面）
   */
  const onFinish = (value: any) => {
    setSearchKey(value.searchKey);
    ref.current?.reload();
  };

  /**
   * @description: 查询重置(将searchKey、TypeAid设置为空，重新渲染表单数据，刷新页面)
   */
  const onReset = () => {
    form.resetFields();
    setTypeAid(undefined);
    setSearchKey(undefined);
    let mounted = true;
    if (mounted) {
      //Do Something
      ref.current?.reload();
    }
    return function cleanup() {
      mounted = false;
    };
  };

  // ProTable列名
  const columns = [
    {
      title: 'ISBN号',
      dataIndex: 'isbn',
      key: 'isbn',
      width: 160,
      height: 56,
    },
    {
      title: '类型',
      dataIndex: 'typeName',
      key: 'typeName',
      width: 157,
      height: 56,
    },
    {
      title: '图书名称',
      dataIndex: 'name',
      key: 'name',
      width: 254,
      height: 56,
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 100,
      height: 56,
      render: (text: any, record: any) => {
        return (
          <Button
            type="link"
            disabled={text === 0 ? true : false}
            onClick={() => {
              setModifyAid(record.aid);
              setOperation(2); //设置操作为图书报损
              setDamageModalVisible(true);
            }}
          >
            {text}
          </Button>
        );
      },
    },
    {
      title: '新增时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 183,
      height: 56,
      render: (value: any) => {
        return formatDate(value, 2);
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      key: 'options',
      width: 320,
      height: 56,
      render: (text: any, record: any) => (
        <div>
          <Button
            type="link"
            size="small"
            id="update"
            onClick={async () => {
              const aid = record.aid;
              await getModalBookInfo(aid);
              setModifyAid(aid);
              setOperation(1); //设置操作为修改
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Button>
          <Popconfirm
            title="你确认要删除该项数据吗？"
            onConfirm={async () => {
              const params = {
                aid: record.aid,
              };
              await delBook(params);
              message.success('删除成功');
              ref.current?.reload();
            }}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link" size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];
  // 搜索表单
  const searchLayout = () => {
    return (
      <div key="searchLayout">
        <Form form={form} onFinish={onFinish} layout="inline">
          <Form.Item name="searchKey" key="searchKey" className={styles.searchKey}>
            <Space>
              <span>图书名称：</span>
              <Input className={styles.searchLayoutInput} allowClear placeholder=" 请输入" />
            </Space>
          </Form.Item>
          <Form.Item name="typeAid">
            <Space>
              <span>类型：</span>
              <Select
                className={styles.searchLayoutSelect}
                placeholder="请选择"
                onChange={(value: any) => {
                  setTypeAid(value);
                }}
                allowClear
              >
                {(bookTypes || []).map((data) => {
                  return (
                    <Select.Option key={data.aid} value={data.aid}>
                      {data.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Space>
          </Form.Item>
          <Form.Item className={styles.searchBtn}>
            <Space>
              <Button name="searchResert" htmlType="button" onClick={onReset}>
                重置
              </Button>
              <Button name="searchQuery" type="primary" htmlType="submit">
                查询
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  };
  // 分页
  const afterTableLayout = () => {
    return (
      <Row justify="end">
        <Col className={styles.tableToolbar}>
          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger
            pageSizeOptions={pageSizeOptions}
            onChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  return (
    <PageContainer>
      <Card className={styles.cardStyle}>{searchLayout()}</Card>
      <Card>
        {/* {beforTableLayout()} */}
        <ProTable
          request={requestHandler}
          actionRef={ref}
          rowKey="aid"
          columns={columns}
          pagination={false}
          headerTitle={[
            <div key="TableTitle" className={styles.titleBox}>
              <span className={styles.titleText}>图书列表</span>
            </div>,
            <div key="bookNumber" className={styles.totalBox}>
              <span className={styles.totalNumber}>{bookNumber}</span>
            </div>,
            <div key="item" className={styles.bookBox}>
              <span className={styles.bookText}>图书总量</span>
            </div>,
          ]}
          toolBarRender={() => [
            <Button
              type="primary"
              id="add"
              onClick={() => {
                setUpdateModalVisible(true);
                setBookInfo(undefined);
                setModifyAid(-1);
                setOperation(0);
                getModalBookInfo();
              }}
            >
              新增
            </Button>,
          ]}
          size="middle"
          search={false}
          options={{ fullScreen: true, setting: false, density: false }}
        />
        {afterTableLayout()}
      </Card>
      <UpdateModal
        operation={operation}
        modifyAid={modifyAid}
        modalVisible={updateModalVisible}
        hideModal={() => {
          setUpdateModalVisible(false);
        }}
        completeOperation={() => {
          setOperation(-1);
        }}
        dataSource={bookInfo}
        treeData={modalBookTypes}
      />
      <BookDemageModal
        modifyAid={modifyAid}
        visible={damageModalVisible}
        hideModal={() => {
          setDamageModalVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default BookManage;
